package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.JwtUtils;
import com.heima.model.media.dtos.WmUserDto;
import com.heima.model.media.dtos.WmUserLoginDto;
import com.heima.wemedia.entity.WmUser;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 自媒体用户信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2022-09-15
 */
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    @Override
    public Integer saveWmUser(WmUserDto dto) {
//        根据apUserId 查询自媒体用户信息
        LambdaQueryWrapper<WmUser> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(WmUser::getApUserId,dto.getApUserId());
        WmUser wmUser = getOne(queryWrapper);
        if(wmUser==null){
            wmUser = new WmUser();
            wmUser.setApUserId(dto.getApUserId());
            wmUser.setName(dto.getName());
            wmUser.setStatus(dto.getStatus());
            wmUser.setCreatedTime(new Date());
        }
        wmUser.setPassword(dto.getPassword());
        wmUser.setPhone(dto.getPhone());
//        新增或修改用户信息
        saveOrUpdate(wmUser);
        return wmUser.getId();
    }

    @Autowired
    private BCryptPasswordEncoder encoder;
    /**
     * 登录
     * @param dto
     * @return
     */
    @Override
    public Map<String, Object> login(WmUserLoginDto dto) {
//        根据用户名查询用户
        LambdaQueryWrapper<WmUser> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(WmUser::getName,dto.getName());
        WmUser wmUser = getOne(queryWrapper);
        if(wmUser ==null){
            log.error("自媒体用户不存在");
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        String password = wmUser.getPassword();
//        判断密码是否正确
        boolean b = encoder.matches(dto.getPassword(), password);
        if(!b){
            log.error("密码不正确");
            throw new LeadException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
//        生成token
        String token = JwtUtils.generateTokenExpireInMinutes(wmUser.getId(), 120);
//        构造返回对象
        wmUser.setPassword(null);
        Map<String,Object> map = new HashMap<>();
        map.put("user",wmUser);
        map.put("token",token);
        return map;
    }
}
